package com.minimalist.lindi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.entity.lindi.po.LindiSubsidyApplicationTownItem;
import com.minimalist.common.entity.lindi.vo.subsidyapplication.LindiSubsidyApplicationTownItemVO;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.mapper.LindiSubsidyApplicationTownItemMapper;
import com.minimalist.lindi.service.LindiSubsidyApplicationTownItemService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.minimalist.common.entity.lindi.po.table.LindiSubsidyApplicationTownItemTableDef.LINDI_SUBSIDY_APPLICATION_TOWN_ITEM;

/**
 * 林地指标交易平台_补贴申请镇街明细 服务层实现。
 *
 * @author 11987
 * @since 2025-01-27
 */
@Service
public class LindiSubsidyApplicationTownItemServiceImpl extends ServiceImpl<LindiSubsidyApplicationTownItemMapper, LindiSubsidyApplicationTownItem> implements LindiSubsidyApplicationTownItemService {

    @Autowired
    private LindiSubsidyApplicationTownItemMapper mapper;

    @Override
    public List<LindiSubsidyApplicationTownItemVO> getSubsidyApplicationTownItemListBySubsidyApplicationId(Long subsidyApplicationId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(LINDI_SUBSIDY_APPLICATION_TOWN_ITEM.SUBSIDY_APPLICATION_ID.eq(subsidyApplicationId));
        List<LindiSubsidyApplicationTownItem> townItemList = list(queryWrapper);
        return BeanUtil.copyToList(townItemList, LindiSubsidyApplicationTownItemVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchAddSubsidyApplicationTownItem(List<LindiSubsidyApplicationTownItemVO> townItemList) {
        if (townItemList == null || townItemList.isEmpty()) {
            return;
        }
        
        for (LindiSubsidyApplicationTownItemVO townItemVO : townItemList) {
            LindiSubsidyApplicationTownItem townItem = BeanUtil.copyProperties(
                    townItemVO, LindiSubsidyApplicationTownItem.class);
            townItem.setSubsidyApplicationTownItem(UnqIdUtil.uniqueId());
            int insert = mapper.insert(townItem, true);
            Assert.isTrue(insert == 1, () -> new BusinessException(
                    "添加镇街明细失败"));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSubsidyApplicationTownItemBySubsidyApplicationId(Long subsidyApplicationId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(LINDI_SUBSIDY_APPLICATION_TOWN_ITEM.SUBSIDY_APPLICATION_ID.eq(subsidyApplicationId));
        remove(queryWrapper);
    }
}